#!/bin/sh

config_script="batocera-config"
log="/userdata/system/logs/batocera.log"

ba_keyboard_lang() {
    settings_lang="$(/usr/bin/batocera-settings-get system.language || echo 'en_US')"
    settings_kb="$(/usr/bin/batocera-settings-get system.kblayout || echo 'us')"
    settings_kb_variant="$(/usr/bin/batocera-settings-get system.kbvariant || echo '')"
    if [ "$settings_kb" != "" ]; then
        loadkeys "$settings_kb" >> $log
    else
        keyboardmap=$(echo "$settings_lang" | cut -c1-2)
        if [ "$keyboardmap" != "" ]; then
            loadkeys "$keyboardmap" >> $log
        fi
    fi
    # Export variables for graphical sessions (Sway, Xorg)
    export XKB_LAYOUT="$settings_kb_layout"
    export XKB_VARIANT="$settings_kb_variant"
}

ba_timezone() {
    settings_timezone="$(/usr/bin/batocera-settings-get system.timezone)"
    if [ "$settings_timezone" != "" ]; then
        eval $config_script "tz" "$settings_timezone" >> $log
    fi
}

ba_hostname() {
    settings_hostname="$(/usr/bin/batocera-settings-get system.hostname)"
    hostname="$(hostname)"
    echo "Hostname after DHCP setup is: ${hostname}" >> /tmp/hostname.log
    if [ "$settings_hostname" != "" ]; then
        echo "Setting hostname from system.hostname: ${settings_hostname}" >> /tmp/hostname.log
        hostname="${settings_hostname}"
        hostname "${settings_hostname}"
    else
        echo "No system.hostname value is set, leaving hostname unchanged" >> /tmp/hostname.log
    fi
    if [ "$hostname" != "" ]; then
        echo "Creating /etc/hosts" >> /tmp/hostname.log
        echo "127.0.0.1	localhost"             > /etc/hosts
        echo "127.0.1.1	${hostname}"          >> /etc/hosts
    fi
    cp /tmp/hostname.log /userdata/system/logs/hostname.log
}

ba_es_core_dump() {
    sysctl -wq kernel.core_pattern=/userdata/system/logs/core.%e
}

case "$1" in
  start)
    printf "Starting system: "
    # Remove carriage return characters from Windows files
    dos2unix /userdata/system/batocera.conf

    export MESA_SHADER_CACHE_DIR="/userdata/system/.cache"

    # configure
    ba_keyboard_lang &
    ba_timezone &
    ba_hostname &
    ba_es_core_dump &
    echo "done."
    ;;
  stop)
    ;;
  restart|reload)
    ;;
  *)
esac

exit $?
